package org.example.m7_14;

import java.util.Stack;

public class Test2 {
    static class ListNode{
        int val;
        ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(9);
        ListNode node2 = new ListNode(8);
        ListNode node3 = new ListNode(7);
        node1.next = node2;
        ListNode node = new Test2().addInList(node1,node3);
        while (node != null){
            System.out.print(node.val);
            node = node.next;
        }
    }
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        ListNode newList = new ListNode(0);
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        while (head1 != null){
            stack1.push(head1.val);
            head1 = head1.next;
        }
        while (head2 != null){
            stack2.push(head2.val);
            head2 =head2.next;
        }
        int r = 0;
        ListNode cur;
        ListNode head = null;
        while (!stack1.isEmpty() || !stack2.isEmpty() || r > 0){
            int num1 = stack1.isEmpty() ? 0 : stack1.pop();
            int num2 = stack2.isEmpty() ? 0 : stack2.pop();
            int sum = num1 + num2 + r;
            if (head == null){
                head = new ListNode(sum % 10);
            }else {
                cur = head;
                head = new ListNode(sum % 10);
                head.next = cur;
            }
            if (sum > 9){
                r = sum / 10;
            }else {
                r = 0;
            }
        }
        newList = head;
        return newList;
    }
}
